// pages/city-list/city-list.js
import * as API_Address from '../../api/address';
const app = getApp();
let log = require('../../log.js'); // 引用上面的log.js文件
let that;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    //当前定位
    currentAddress: {},
    myLocation: '',
    myLocationData: {},
    latitude: '',
    longitude: '',
    // 最近使用
    historyList: [],
    // 附近地址
    nearList: []
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    let { currentAddress } = this.data;
    currentAddress = app.globalData.locationData;
    this.setData({
      currentAddress
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getMyLocation();
    let _history = wx.getStorageSync('locationHistory');
    if (_history.length) {
      _history.shift();
    };
    this.setData({
      historyList: _history || []
    });
  },
  // 获取当前经纬度
  getMyLocation () {
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        let lat = res.latitude;
        let lng = res.longitude;
        that.setData({
          latitude: lat,
          longitude: lng
        });
        that.getNearby(lng, lat);
      },fail: function (error) {
        log.error(error);
        wx.showToast({
          title: '获取定位信息失败',
          icon: 'none'
        });
        setTimeout(() => {
          wx.hideToast();
        }, 1500);
      }
    })
  },
  // 获取定位附近地标
  getNearby (lng, lat) {
    API_Address.getNearby(lng, lat).then(res => {
      let _nearList = res.pois || res.pois;
      // 最多附近10个建筑
      if (res.pois && res.pois.length > 10) {
        _nearList = res.pois.length > 10 ? res.pois.slice(0, 10) : res.pois;
      };
      this.setData({
        myLocation: res.address || '',
        myLocationData: {
          ...res.location,
          ...res.address_component,
          title: res.formatted_addresses.recommend
        },
        nearList: _nearList
      });
    }).catch(error => {
      log.error(error);
    });
  },
  // 显示地图地址
  showMap () {
    wx.chooseLocation({
      success: function (res) {
        if (res.address && res.name) {
          that.formatAddress(res.longitude, res.latitude);
        }
      },fail: function (error) {
        log.error(error);
      }
    });
  },
  // 地址选择回显
  formatAddress (longitude, latitude) {
    API_Address.getNearby(longitude, latitude).then(resposnse => {
      const { address, address_component, formatted_addresses, location } = resposnse;
      const { province, city, district } = address_component;
      const name = formatted_addresses.recommend;
      const { lat, lng } = location;
      let addressAct = { 
        'hasAuth': true,
        'latitude': lat,
        'longitude': lng,
        'address': address,
        'addressName': name,
        'buildingPosition': `${lng},${lat}`,
        'province': province,
        'city': !city ? province : city,
        'district': district,
        'detailAddress': address
      };
      app.globalData.locationData = addressAct;
      wx.navigateBack({ delta: 1 })
      getCurrentPages()[getCurrentPages().length - 2].onLoad();
      getCurrentPages()[getCurrentPages().length - 2].onShow();
    }).catch(error => {
      log.error(error);
    });
  },
  // 地址选择确认
  async addressSub (e) {
    let _type = e.currentTarget.dataset.type;
    if (!_type) {
      wx.navigateBack();
    } else {
      let addressAct = {};
      let { longitude, latitude } = this.data;
      switch (_type) {
        case 'location': // 当前定位
          const { myLocation, myLocationData } = this.data;
          const { province, city, district } = myLocationData;
          addressAct = {
            'address': myLocation,
            'addressName': myLocationData.title,
            'province': province,
            'city': !city ? province : city,
            'district': district,
            'detailAddress': myLocation
          };
          break;
        case 'history': // 最近使用
          const _actHistory = e.currentTarget.dataset.address;
          longitude = _actHistory.longitude;
          latitude = _actHistory.latitude;
          addressAct = {
            'address': _actHistory.address,
            'addressName':  _actHistory.addressName,
            'province': _actHistory.province,
            'city': _actHistory.city || _actHistory.province,
            'district': _actHistory.district,
            'detailAddress': _actHistory.detailAddress
          };
          break;
        case 'near': // 附近
          const { ad_info, address, location, title } = e.currentTarget.dataset.address;
          longitude = location.lng;
          latitude = location.lat;
          addressAct = {
            'address': address,
            'addressName':  title,
            'province': ad_info.province,
            'city': ad_info.city || ad_info.province,
            'district': ad_info.district,
            'detailAddress': address
          };
          break;   
      };
      addressAct.hasAuth = true;
      addressAct = {
        ...addressAct,
        longitude,
        latitude,
        'hasAuth': true,
        'buildingPosition': `${longitude},${latitude}`,
      };
      app.globalData.locationData = addressAct;
      wx.navigateBack();
      getCurrentPages()[getCurrentPages().length - 2].onLoad();
      getCurrentPages()[getCurrentPages().length - 2].onShow();
    };
  }
})